/*
  MinCC - Minimalist Compiler Collection
  Copyright (C) 2009 Scott Lawrence

  MinCC is free software: you can redistribute it and/or modify it
  under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  MinCC is distributed in the hope that it will be useful, but WITHOUT
  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
  or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
  License for more details.

  You should have received a copy of the GNU General Public License
  along with mincc.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <stdio.h>
#include <string.h>
#include <string>
using namespace std;

#include "error.hpp"
#include "fileLoader.hpp"

FileLoader::FileLoader() {
    count=0;max=2;
    path=new char*[max];
    setPath(".");
}

FileLoader::FileLoader(const char *p) {
    count=0;max=2;
    path=new char*[max];
    setPath(p);
}

FileLoader::~FileLoader() {

}

FILE *FileLoader::openFile(const char *name) {
    IERROR(11);
    return 0;
}

char *FileLoader::getCode(const char *name) {
    IERROR(11);
    FILE *fin=openFile(name);
    if(!fin)
        ERROR;

    fclose(fin);
    return 0;
}

void FileLoader::addSingleToPath(char *p) {
    char *t=new char[strlen(p)+1];
    strcpy(t,p);
    if(count==max) {
        char **temp=path;
        max*=2;
        path=new char*[max];
        for(int i=0;i<count;i++)
            path[i]=temp[i];
    }
    path[count]=t;
    count++;
}

void FileLoader::addToPath(const char *p) {
    char *a=new char[strlen(p)+1];
    strcpy(a,p);
    addToPath(a);
}

void FileLoader::addToPath(char *a) {
    char *p=new char[strlen(a)+2];
    strcpy(p,a);
    p[strlen(a)]=':';
    char *pch=strtok(p,":");
    while(pch!=NULL) {
        addSingleToPath(pch);
        pch=strtok(NULL,":");
    }
}

void FileLoader::setPath(const char *p) {
    char *a=new char[strlen(p)+1];
    strcpy(a,p);
    setPath(a);
}

void FileLoader::setPath(char *a) {
    char *p=new char[strlen(a)+2];
    strcpy(p,a);
    p[strlen(a)]=':';
    path=new char*[max];count=0;
    char *pch=strtok(p,":");
    while(pch!=NULL) {
        addSingleToPath(pch);
        pch=strtok(NULL,":");
    }
}

char *FileLoader::getPath() {
    string r="";
    if(count==0) return (char *)r.data();
    r+=path[0];
    for(int i=1;i<count;i++)
        r+=string(":")+path[i];
    return (char *)r.data();
}

char **FileLoader::getPathList() {
    return path;
}

int FileLoader::getPathSize() {
    return count;
}
